﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SuperMap.Mapping;
using SuperMap.Data;
using System.IO;
using SuperMap.Desktop.UI;
using SuperMap.Desktop;

namespace SuperMap.HB.ThemeWork
{
    public partial class PointThemeControl : UserControl
    {
        public PointThemeType ThemeType { get; set; } = PointThemeType.Unique;

        private PointInfo m_PointInfo = new PointInfo();
        private const string m_DataSourceName = "点数据";
        private Datasource m_DataSource = Desktop.Application.ActiveApplication.Workspace.Datasources[m_DataSourceName];
        private List<double> m_RangelstValues;

        public PointThemeControl()
        {
            InitializeComponent();

            groupBox1.Paint += groupBox_Paint;
            groupBox2.Paint += groupBox_Paint;
            gb_Graph.Paint += groupBox_Paint;
            gb_Range.Paint += groupBox_Paint;
            gb_Unique.Paint += groupBox_Paint;
        }

        private void groupBox_Paint(object sender, PaintEventArgs e)
        {
            try
            {
                GroupBox gBox = (GroupBox)sender;

                e.Graphics.Clear(gBox.BackColor);
                e.Graphics.DrawString(gBox.Text, gBox.Font, Brushes.Black, 10, 1);
                var vSize = e.Graphics.MeasureString(gBox.Text, gBox.Font);
                e.Graphics.DrawLine(Pens.Black, 1, vSize.Height / 2, 8, vSize.Height / 2);
                e.Graphics.DrawLine(Pens.Black, vSize.Width + 8, vSize.Height / 2, gBox.Width - 2, vSize.Height / 2);
                e.Graphics.DrawLine(Pens.Black, 1, vSize.Height / 2, 1, gBox.Height - 2);
                e.Graphics.DrawLine(Pens.Black, 1, gBox.Height - 2, gBox.Width - 2, gBox.Height - 2);
                e.Graphics.DrawLine(Pens.Black, gBox.Width - 2, vSize.Height / 2, gBox.Width - 2, gBox.Height - 2);
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void PointThemeControl_Load(object sender, EventArgs e)
        {
            try
            {
                cmb_SelectMap.Items.Clear();
                foreach (string map in Desktop.Application.ActiveApplication.Workspace.Maps)
                {
                    cmb_SelectMap.Items.Add(map);
                }
                if (cmb_SelectMap.Items.Count > 0)
                {
                    cmb_SelectMap.SelectedIndex = 0;
                    groupBox1.Enabled = true;
                    groupBox2.Enabled = true;
                    gb_Graph.Enabled = true;
                    gb_Range.Enabled = true;
                    gb_Unique.Enabled = true;
                    btn_OK.Enabled = true;
                }
                else
                {
                    groupBox1.Enabled = false;
                    groupBox2.Enabled = false;
                    gb_Graph.Enabled = false;
                    gb_Range.Enabled = false;
                    gb_Unique.Enabled = false;
                    btn_OK.Enabled = false;
                }

                cmb_SelectData.Items.Clear();
                foreach (Dataset dt in m_DataSource.Datasets)
                {
                    if (dt.Type == DatasetType.Point)
                    {
                        cmb_SelectData.Items.Add(dt.Name);
                    }
                }
                if (cmb_SelectData.Items.Count > 0)
                {
                    m_PointInfo.DatasetName = cmb_SelectData.Items[0].ToString();
                    cmb_SelectData.SelectedIndex = 0;
                }

                switch (ThemeType)
                {
                    case PointThemeType.Unique:
                        gb_Unique.Visible = true;
                        gb_Range.Visible = false;
                        gb_Graph.Visible = false;
                        gb_Unique.Text = "单值专题图";
                        break;
                    case PointThemeType.Graph:
                        gb_Unique.Visible = false;
                        gb_Range.Visible = false;
                        gb_Graph.Visible = true;
                        break;
                    case PointThemeType.Range:
                        gb_Unique.Visible = false;
                        gb_Range.Visible = true;
                        gb_Graph.Visible = false;
                        cmb_RangeMode.SelectedIndex = 0;
                        break;
                    case PointThemeType.Label:
                        gb_Unique.Visible = true;
                        gb_Range.Visible = false;
                        gb_Graph.Visible = false;
                        gb_Unique.Text = "标签专题图";
                        break;
                }
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            try
            {
                MessageTip tip = new MessageTip();
                tip.ShowTip();
                Theme theme = null;
                ColorScheme colorScheme;
                string xml = "";
                string line = "";
                StreamReader sr;
                TextStyle textStyle;
                switch (ThemeType)
                {
                    case PointThemeType.Unique:
                        ThemeUnique themeUnique = new ThemeUnique
                        {
                            UniqueExpression = m_PointInfo.ThemeFieldName,
                            IsDefaultStyleVisible = false
                        };

                        Recordset objRt = null;
                        List<string> lstValues = new List<string>();

                        try
                        {
                            objRt = (m_DataSource.Datasets[m_PointInfo.DatasetName] as DatasetVector).GetRecordset(false, CursorType.Static);
                            objRt.MoveFirst();
                            while (!objRt.IsEOF)
                            {
                                if (objRt.GetFieldValue(m_PointInfo.ThemeFieldName) != null)
                                {
                                    string value = Convert.ToString(objRt.GetFieldValue(m_PointInfo.ThemeFieldName));
                                    List<string> exist = lstValues.FindAll(delegate (string s) { return s.Equals(value); });
                                    if (exist.Count == 0)
                                    {
                                        lstValues.Add(value);
                                    }
                                }

                                objRt.MoveNext();
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.OutputBox(ex);
                        }
                        finally
                        {
                            if (objRt != null)
                            {
                                objRt.Close();
                                objRt.Dispose();
                            }
                        }
                        
                        colorScheme = new ColorScheme();
                        xml = "";
                        line = "";
                        sr = new StreamReader(AppDomain.CurrentDomain.BaseDirectory.Substring(0, AppDomain.CurrentDomain.BaseDirectory.Length - 4) + @"Templates\ColorScheme\Default\Map_ThemeUnique\LE_Draw.scs");
                        while ((line = sr.ReadLine()) != null)
                        {
                            xml += line;
                        }
                        colorScheme.FromXML(xml);

                        for(int i = 0; i < lstValues.Count; i++)
                        {
                            GeoStyle style = new GeoStyle
                            {
                                LineColor = colorScheme.KeyColors[i],
                                MarkerSize = new Size2D(5, 5)
                            };
                            ThemeUniqueItem item = new ThemeUniqueItem
                            {
                                Unique = lstValues[i],
                                Caption = lstValues[i],
                                Style = style
                            };
                            themeUnique.Add(item);
                        }
                        
                        theme = themeUnique;
                        break;
                    case PointThemeType.Graph:
                        textStyle = new TextStyle
                        {
                            ForeColor = Color.Black,
                            Alignment = TextAlignment.BottomCenter
                        };
                        ThemeGraph themeGraph = new ThemeGraph
                        {
                            IsFlowEnabled = false,
                            IsGraphSizeFixed = false,
                            IsGraphTextDisplayed = true,
                            GraphTextStyle = textStyle,
                            GraphTextFormat = ThemeGraphTextFormat.Value,
                            MaxGraphSize = Convert.ToDouble(txt_MaxValue.Text.Trim()),
                            MinGraphSize = Convert.ToDouble(txt_Min.Text.Trim())
                        };
                        if (rdo_Bar.Checked)
                        {
                            themeGraph.GraphType = ThemeGraphType.Bar;
                        }
                        if (rdo_Pie.Checked)
                        {
                            themeGraph.GraphType = ThemeGraphType.Pie;
                        }
                        colorScheme = new ColorScheme();
                        xml = "";
                        line = "";
                        sr = new StreamReader(AppDomain.CurrentDomain.BaseDirectory.Substring(0, AppDomain.CurrentDomain.BaseDirectory.Length - 4) + @"Templates\ColorScheme\Default\Map_ThemeGraph\HD_Luck.scs");
                        while ((line = sr.ReadLine()) != null)
                        {
                            xml += line;
                        }
                        colorScheme.FromXML(xml);
                        int colorIndex = 0;
                        for (int i = 0; i < dgv_Graph.Rows.Count; i++)
                        {
                            if (Convert.ToBoolean((dgv_Graph.Rows[i].Cells[0] as DataGridViewCheckBoxCell).Value))
                            {
                                GeoStyle style = new GeoStyle
                                {
                                    FillForeColor = colorScheme.KeyColors[colorIndex++],
                                };
                                ThemeGraphItem item = new ThemeGraphItem
                                {
                                    GraphExpression = Convert.ToString((dgv_Graph.Rows[i].Cells[1] as DataGridViewTextBoxCell).Value),
                                    Caption = Convert.ToString((dgv_Graph.Rows[i].Cells[1] as DataGridViewTextBoxCell).Value),
                                    UniformStyle = style
                                };
                                themeGraph.Add(item);
                            }
                        }

                        theme = themeGraph;
                        break;
                    case PointThemeType.Range:
                        ThemeRange themeRange = new ThemeRange
                        {
                            RangeExpression = m_PointInfo.ThemeFieldName
                        };

                        colorScheme = new ColorScheme();
                        xml = "";
                        line = "";
                        sr = new StreamReader(AppDomain.CurrentDomain.BaseDirectory.Substring(0, AppDomain.CurrentDomain.BaseDirectory.Length - 4) + @"Templates\ColorScheme\Default\Map_ThemeRange\ZO_Precipitation 4.scs");
                        while ((line = sr.ReadLine()) != null)
                        {
                            xml += line;
                        }
                        colorScheme.FromXML(xml);

                        for (int i = 0; i < dgv_Range.Rows.Count; i++)
                        {
                            if ((dgv_Range.Rows[i].Cells[2] as DataGridViewTextBoxCell).Value == null)
                            {
                                continue;
                            }
                            GeoStyle style = new GeoStyle
                            {
                                LineColor = colorScheme.KeyColors[i],
                                MarkerSize = new Size2D(5, 5)
                            };
                            ThemeRangeItem item = new ThemeRangeItem
                            {
                                Caption = Convert.ToString((dgv_Range.Rows[i].Cells[2] as DataGridViewTextBoxCell).Value),
                                Start = Convert.ToDouble((dgv_Range.Rows[i].Cells[0] as DataGridViewTextBoxCell).Value),
                                End = Convert.ToDouble((dgv_Range.Rows[i].Cells[1] as DataGridViewTextBoxCell).Value),
                                Style = style
                            };
                            themeRange.AddToTail(item);
                        }
                        GeoStyle styleLast = new GeoStyle
                        {
                            LineColor = colorScheme.KeyColors[dgv_Range.Rows.Count],
                            MarkerSize = new Size2D(5, 5)
                        };
                        ThemeRangeItem itemLast = new ThemeRangeItem
                        {
                            Caption = (dgv_Range.Rows.Count + 1).ToString(),
                            Start = m_RangelstValues.Max(),
                            Style = styleLast
                        };
                        themeRange.AddToTail(itemLast);

                        theme = themeRange;
                        break;
                    case PointThemeType.Label:
                        textStyle = new TextStyle
                        {
                            ForeColor = Color.Black,
                            IsSizeFixed = true,
                            FontHeight = 4.25,
                            FontName = "Microsoft YaHei UI"
                        };

                        ThemeLabel themeLabel = new ThemeLabel
                        {
                            LabelExpression = cmb_UniqueField.Text.Trim(),
                            UniformStyle = textStyle
                        };

                        theme = themeLabel;

                        break;
                }
                if (theme != null)
                {
                    Desktop.Application.ActiveApplication.MainForm.FormManager.CloseAll(false);
                    Map map = Desktop.Application.ActiveApplication.CreateMapWindow().MapControl.Map;
                    map.Open(cmb_SelectMap.Text);
                    DatasetVector dtv = m_DataSource.Datasets[m_PointInfo.DatasetName] as DatasetVector;
                    map.Layers.Add(dtv, theme, true);

                    if (chk_UseLabelTheme.Checked)
                    {
                        TextStyle labelStyle = new TextStyle
                        {
                            ForeColor = Color.Black,
                            IsSizeFixed = true,
                            FontHeight = 4.25,
                            FontName = "Microsoft YaHei UI"
                        };
                        ThemeLabel themeLabel = new ThemeLabel
                        {
                            LabelExpression = cmb_LabelField.Text.Trim(),
                            UniformStyle = labelStyle
                        };
                        map.Layers.Add(dtv, themeLabel, true);
                    }

                    bool exist = false;
                    foreach (string mapname in Desktop.Application.ActiveApplication.Workspace.Maps)
                    {
                        if (mapname.Equals(cmb_SelectMap.Text.Trim()))
                        {
                            exist = true;
                            break;
                        }
                    }
                    if (exist)
                    {
                        Desktop.Application.ActiveApplication.Workspace.Maps.SetMapXML(cmb_SelectMap.Text.Trim(), map.ToXML());
                    }
                    else
                    {
                        Desktop.Application.ActiveApplication.Workspace.Maps.Add(cmb_SelectMap.Text.Trim(), map.ToXML());
                    }
                    if (Desktop.Application.ActiveApplication.Workspace.Save())
                    {
                        tip.HideTip();
                        Desktop.Application.ActiveApplication.MessageBox.Show("保存成功！");
                    }
                    else
                    {
                        tip.HideTip();
                        Desktop.Application.ActiveApplication.MessageBox.Show("保存失败！");
                    }

                }
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void cmb_SelectMap_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                m_PointInfo.MapName = cmb_SelectMap.Text;
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void rdo_SelectData_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (rdo_SelectData.Checked)
                {
                    txt_SelectPath.Visible = false;
                    btn_SelectPath.Visible = false;
                    cmb_SelectData.Visible = true;

                    cmb_SelectData.Items.Clear();
                    foreach (Dataset dt in m_DataSource.Datasets)
                    {
                        if (dt.Type == DatasetType.Point)
                        {
                            cmb_SelectData.Items.Add(dt.Name);
                        }
                    }
                    if (cmb_SelectData.Items.Count > 0)
                    {
                        m_PointInfo.DatasetName = cmb_SelectData.Items[0].ToString();
                        cmb_SelectData.SelectedIndex = 0;
                    }
                }
                if (rdo_ImportData.Checked)
                {
                    txt_SelectPath.Visible = true;
                    btn_SelectPath.Visible = true;
                    cmb_SelectData.Visible = false;
                }
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void cmb_Field_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                m_PointInfo.ThemeFieldName = cmb_UniqueField.Text;
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void cmb_SelectData_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(m_PointInfo.DatasetName))
                {
                    Desktop.Application.ActiveApplication.MessageBox.Show("请设置点数据！");
                    return;
                }
                if (!(m_DataSource.Datasets[m_PointInfo.DatasetName] is DatasetVector dtv))
                {
                    Desktop.Application.ActiveApplication.MessageBox.Show("数据集可能被损坏，请选择其他数据集！");
                    return;
                }
                switch (ThemeType)
                {
                    case PointThemeType.Unique:
                    case PointThemeType.Label:
                        cmb_UniqueField.Items.Clear();
                        foreach (FieldInfo info in dtv.FieldInfos)
                        {
                            if (!info.Name.ToLower().Contains("sm"))
                            {
                                cmb_UniqueField.Items.Add(info.Name);
                            }
                        }
                        if (cmb_UniqueField.Items.Count > 0)
                        {
                            cmb_UniqueField.SelectedIndex = 0;
                        }
                        break;
                    case PointThemeType.Graph:
                        dgv_Graph.Rows.Clear();
                        foreach (FieldInfo info in dtv.FieldInfos)
                        {
                            if (!info.Name.ToLower().Contains("sm"))
                            {
                                DataGridViewRow row = new DataGridViewRow();
                                row.Cells.Add(new DataGridViewCheckBoxCell());
                                row.Cells.Add(new DataGridViewTextBoxCell { Value = info.Name });
                                dgv_Graph.Rows.Add(row);
                            }
                        }
                        break;
                    case PointThemeType.Range:
                        cmb_RangeField.Items.Clear();
                        foreach (FieldInfo info in dtv.FieldInfos)
                        {
                            if (!info.Name.ToLower().Contains("sm"))
                            {
                                cmb_RangeField.Items.Add(info.Name);
                            }
                        }
                        if (cmb_RangeField.Items.Count > 0)
                        {
                            cmb_RangeField.SelectedIndex = 0;
                        }
                        break;
                }
                cmb_LabelField.Items.Clear();
                foreach (FieldInfo info in dtv.FieldInfos)
                {
                    if (!info.Name.ToLower().Contains("sm"))
                    {
                        cmb_LabelField.Items.Add(info.Name);
                    }
                }
                if (cmb_LabelField.Items.Count > 0)
                {
                    cmb_LabelField.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void cmb_RangeField_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                m_PointInfo.ThemeFieldName = cmb_RangeField.Text;
                CalculateRange();
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void cmb_RangeMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                switch (cmb_RangeMode.SelectedIndex)
                {
                    case 0:
                        m_PointInfo.RangeMode= RangeMode.EqualInterval;
                        txt_RangeCount.ReadOnly = false;
                        foreach (DataGridViewRow row in dgv_Range.Rows)
                        {
                            row.Cells[0].ReadOnly = true;
                            row.Cells[1].ReadOnly = true;
                        }
                        dgv_Range.AllowUserToAddRows = false;
                        dgv_Range.AllowUserToDeleteRows = false;
                        break;
                    case 1:
                        m_PointInfo.RangeMode = RangeMode.CustomInterval;
                        txt_RangeCount.ReadOnly = true;
                        foreach (DataGridViewRow row in dgv_Range.Rows)
                        {
                            row.Cells[0].ReadOnly = false;
                            row.Cells[1].ReadOnly = false;
                        }
                        dgv_Range.AllowUserToAddRows = true;
                        dgv_Range.AllowUserToDeleteRows = true;
                        break;
                }
                CalculateRange();
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void txt_RangeCount_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (m_PointInfo.RangeMode == RangeMode.EqualInterval)
                {
                    CalculateRange();
                }
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void CalculateRange()
        {
            Recordset objRt = null;

            try
            {
                if (m_PointInfo.RangeMode == RangeMode.CustomInterval)
                {
                    if (string.IsNullOrEmpty(txt_RangeLength.Text))
                    {
                        Desktop.Application.ActiveApplication.MessageBox.Show("请设置单段长度！");
                        return;
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(txt_RangeCount.Text))
                    {
                        Desktop.Application.ActiveApplication.MessageBox.Show("请设置段数！");
                        return;
                    }
                }
                objRt = (m_DataSource.Datasets[m_PointInfo.DatasetName] as DatasetVector).GetRecordset(false, CursorType.Static);
                objRt.MoveFirst();
                if (m_RangelstValues == null)
                {
                    m_RangelstValues = new List<double>();
                }
                m_RangelstValues.Clear();
                while (!objRt.IsEOF)
                {
                    if (objRt.GetFieldValue(cmb_RangeField.Text) != null)
                    {
                        double value = Convert.ToDouble(objRt.GetFieldValue(cmb_RangeField.Text));
                        m_RangelstValues.Add(value);
                    }

                    objRt.MoveNext();
                }
                double dMax = m_RangelstValues.Max();
                double dMin = m_RangelstValues.Min();
                
                switch (m_PointInfo.RangeMode)
                {
                    case RangeMode.EqualInterval:
                        int count = Convert.ToInt32(txt_RangeCount.Text);
                        double length = (dMax - dMin) / count;
                        txt_RangeLength.Text = length.ToString();

                        dgv_Range.Rows.Clear();
                        for (int i = 0; i < count; i++)
                        {
                            DataGridViewRow row = new DataGridViewRow();
                            row.Cells.Add(new DataGridViewTextBoxCell { Value = (dMin + (i * length)) });
                            row.Cells.Add(new DataGridViewTextBoxCell { Value = (dMin + ((i + 1) * length)) });
                            row.Cells.Add(new DataGridViewTextBoxCell { Value = (i + 1).ToString() });
                            dgv_Range.Rows.Add(row);
                        }
                        break;
                    case RangeMode.CustomInterval:

                        break;
                }
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
            finally
            {
                if (objRt != null)
                {
                    objRt.Close();
                    objRt.Dispose();
                }
            }
        }

        private void btn_SelectPath_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog open = new OpenFileDialog
                {
                    Filter = "所有文件|*.*|Shapefile文件|*.shp|Excel文件|*.xlsx|Excel文件|*.xls",
                    Multiselect = false
                };
                if (open.ShowDialog() == DialogResult.OK)
                {
                    string ext = open.SafeFileName.Split('.')[1];
                    switch (ext)
                    {
                        case "xlsx":
                        case "xls":
                            ExcelHelper excel = new ExcelHelper();
                            DataSet ds = excel.FromFile(open.FileName);
                            if (CheckData.ConfirmData(ds))
                            {
                                MessageTip tip = new MessageTip();
                                tip.ShowTip();
                                foreach (DataTable dt in ds.Tables)
                                {
                                    DatasetVectorInfo vectorInfo = new DatasetVectorInfo
                                    {
                                        Type = DatasetType.Point,
                                        Name = m_DataSource.Datasets.GetAvailableDatasetName(dt.TableName),
                                    };
                                    DatasetVector vector = m_DataSource.Datasets.Create(vectorInfo);
                                    m_PointInfo.DatasetName = vectorInfo.Name;
                                    vector.PrjCoordSys = m_DataSource.PrjCoordSys;

                                    //新建属性
                                    List<string> lstFields = new List<string>();
                                    foreach (DataColumn col in dt.Columns)
                                    {
                                        FieldInfo info = new FieldInfo
                                        {
                                            Name = col.ColumnName,
                                            Caption = col.ColumnName,
                                            Type = FieldType.WText
                                        };
                                        if (vector.FieldInfos.IndexOf(col.ColumnName) < 0)
                                        {
                                            vector.FieldInfos.Add(info);
                                        }
                                        lstFields.Add(col.ColumnName);
                                    }

                                    SelectFieldForm selectFieldForm = new SelectFieldForm
                                    {
                                        Fields = lstFields
                                    };
                                    tip.HideTip();
                                    if (selectFieldForm.ShowDialog() == DialogResult.OK)
                                    {
                                        tip.ShowTip();
                                        //添加数据
                                        Recordset objRt = vector.GetRecordset(true, CursorType.Dynamic);

                                        try
                                        {
                                            Recordset.BatchEditor editor = objRt.Batch;
                                            editor.MaxRecordCount = 50;
                                            editor.Begin();

                                            foreach (DataRow row in dt.Rows)
                                            {
                                                Dictionary<string, object> dic = new Dictionary<string, object>();
                                                foreach (DataColumn col in dt.Columns)
                                                {
                                                    string value = row[col].ToString();
                                                    dic.Add(col.ColumnName, value);
                                                }

                                                GeoPoint point = new GeoPoint
                                                {
                                                    X = Convert.ToDouble(row[selectFieldForm.LonName]),
                                                    Y = Convert.ToDouble(row[selectFieldForm.LatName])
                                                };
                                                bool b = objRt.AddNew(point, dic);
                                            }

                                            editor.Update();
                                        }
                                        catch (Exception ex)
                                        {
                                            Log.OutputBox(ex);
                                        }
                                        finally
                                        {
                                            objRt?.Close();
                                            objRt?.Dispose();
                                        }
                                    }
                                }
                                Import_OnImportFinished(null, null);
                                tip.HideTip();
                                Desktop.Application.ActiveApplication.MessageBox.Show("导入成功！");
                            }
                            else
                            {
                                Desktop.Application.ActiveApplication.MessageBox.Show("数据表结构不适用，请修正数据后重试！");
                                return;
                            }
                            break;
                        case "shp":
                            txt_SelectPath.Text = open.FileName;
                            string datasetName = m_DataSource.Datasets.GetAvailableDatasetName((new FileInfo(txt_SelectPath.Text)).Name.Split('.')[0]);
                            m_PointInfo.DatasetName = datasetName;
                            ImportDataManager import = new ImportDataManager();
                            import.OnImportFinished += Import_OnImportFinished;
                            import.Import(m_DataSourceName, datasetName, open.FileName);
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void Import_OnImportFinished(object sender, EventArgs e)
        {
            try
            {
                DatasetVector dtv = m_DataSource.Datasets[m_PointInfo.DatasetName] as DatasetVector;
                switch (ThemeType)
                {
                    case PointThemeType.Unique:
                    case PointThemeType.Label:
                        cmb_UniqueField.Items.Clear();
                        foreach (FieldInfo info in dtv.FieldInfos)
                        {
                            if (!info.Name.ToLower().Contains("sm"))
                            {
                                cmb_UniqueField.Items.Add(info.Name);
                            }
                        }
                        if (cmb_UniqueField.Items.Count > 0)
                        {
                            cmb_UniqueField.SelectedIndex = 0;
                        }
                        break;
                    case PointThemeType.Graph:
                        dgv_Graph.Rows.Clear();
                        foreach (FieldInfo info in dtv.FieldInfos)
                        {
                            if (!info.Name.ToLower().Contains("sm"))
                            {
                                DataGridViewRow row = new DataGridViewRow();
                                row.Cells.Add(new DataGridViewCheckBoxCell());
                                row.Cells.Add(new DataGridViewTextBoxCell { Value = info.Name});
                                dgv_Graph.Rows.Add(row);
                                row.Cells[1].ReadOnly = true;
                            }
                        }
                        break;
                    case PointThemeType.Range:
                        cmb_RangeField.Items.Clear();
                        foreach (FieldInfo info in dtv.FieldInfos)
                        {
                            if (!info.Name.ToLower().Contains("sm"))
                            {
                                cmb_RangeField.Items.Add(info.Name);
                            }
                        }
                        if (cmb_RangeField.Items.Count > 0)
                        {
                            cmb_RangeField.SelectedIndex = 0;
                        }
                        break;
                }
                cmb_LabelField.Items.Clear();
                foreach (FieldInfo info in dtv.FieldInfos)
                {
                    if (!info.Name.ToLower().Contains("sm"))
                    {
                        cmb_LabelField.Items.Add(info.Name);
                    }
                }
                if (cmb_LabelField.Items.Count > 0)
                {
                    cmb_LabelField.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void dgv_Range_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                try
                {
                    Convert.ToDouble(dgv_Range.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
                }
                catch
                {
                    Desktop.Application.ActiveApplication.MessageBox.Show("请输入正确数值！");
                    dgv_Range.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = null;
                    return;
                }
                double value = Convert.ToDouble(dgv_Range.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
                if (value > m_RangelstValues.Max())
                {
                    Desktop.Application.ActiveApplication.MessageBox.Show("输入的数值不能大于最大值（" + m_RangelstValues.Max() + "）！");
                    dgv_Range.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = null;
                    return;
                }
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void btn_SelectAll_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (DataGridViewRow row in dgv_Graph.Rows)
                {
                    (row.Cells[0] as DataGridViewCheckBoxCell).Value = true;
                }
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void btn_SelectChange_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (DataGridViewRow row in dgv_Graph.Rows)
                {
                    (row.Cells[0] as DataGridViewCheckBoxCell).Value = !Convert.ToBoolean((row.Cells[0] as DataGridViewCheckBoxCell).Value);
                }
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void chk_UserLabelTheme_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                cmb_LabelField.Enabled = chk_UseLabelTheme.Checked;
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void btn_SetStyle_Click(object sender, EventArgs e)
        {
            try
            {

            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }
    }

    public enum PointThemeType
    {
        Unique,
        Graph,
        Range,
        Label
    }
}
